//
//  CZOAuthViewController.swift
//  CZWeibo
//
//  Created by 左凯旭 on 16/8/10.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking
class CZOAuthViewController: UIViewController {

    override func loadView() {
        
        view = webView
              // 判断url 是否为nil
        guard let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBredirect_uri)") else{
            return
        }
        
        webView.delegate = self
        
        //打印字符串
//        print(url.absoluteString)
        
        let request = NSURLRequest(URL: url)
        webView.loadRequest(request)
    }
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

       setupUI()
    }
    
    //MARK: - 导航栏按钮监听
    @objc private func cancelClick(){
        dismissViewControllerAnimated(false, completion: nil)
    }
    
    @objc private func autoClick(){
        
//        print("自动填充")
        let jsString = "document.getElementById('userId').value='\(WBName)',document.getElementById('passwd').value='\(WBPassWd)'"
         // js注入
        
        webView.stringByEvaluatingJavaScriptFromString(jsString)
        
    }
    

    //设置UI
    private func setupUI(){
        setupNav()
        view.backgroundColor = UIColor.whiteColor()
    
    }
    //设置导航栏
    func setupNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelClick")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoClick")
        navigationItem.title = "微博登陆"
    }
    
    //MARK: - 懒加载webView
    private lazy var webView:UIWebView = UIWebView()
    
    
    
}

extension CZOAuthViewController:UIWebViewDelegate{
    
    /*
     - 监听 webView 将要加载的request
     - 如果不实现 默认 返回true
     - 如果返回 false  停止加载requet
     */
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //        let urlString = request.URL?.absoluteString
        
        // 判断urlString 是否为nil  而且 它的前缀是否为我们设置的回调页
        if let urlString = request.URL?.absoluteString where urlString.hasPrefix(WBredirect_uri){
            // query 请求参数
            // 判断是否为nil
            if let query = request.URL?.query{
                
                let code = query.substringFromIndex("code=".endIndex)
//                print(code)
                //请求数据
//                getUserAccount(code)
                
                //访问viewModel中的请求方法
                CZUserAccountViewModel.shareTools.getUserAccount(code, finish: { (isSuccess) in
                    if !isSuccess {
                        print("请求失败")
                        return
                    }
                    print("请求成功")
//                    let result = CZUserAccountViewModel.shareTools.userAccount
//                    print(result)
                    self.dismissViewControllerAnimated(true, completion: { 
                        
                        NSNotificationCenter.defaultCenter().postNotificationName(WBSWITCHROOTVCNOTIFICATION, object: "oauth")
                    })
                    
                    
                })
                return false
            }
            
        }
  
        return true
    }
    
    
    //开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    //加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    //加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
    }
    
}












